import java.util.PriorityQueue;

class TimerTask implements Comparable<TimerTask>{
    private long time;//任务执行的时间
    private Runnable runnable;//任务执行的内容
    public TimerTask(long time,Runnable runnable){
        this.time = System.currentTimeMillis()+ time;//传入时间
        this.runnable = runnable;//传入任务
    }
    public void run(){//执行任务
        runnable.run();
    }
    public long getTime(){//获取时间戳
        return  time;
    }

    @Override
    public int compareTo(TimerTask o) {//比较规则
        return (int) (this.time-o.time);
    }
}
class Timer{//存任务，创建线程执行任务。
    public static Object loker1 = new Object();
    private PriorityQueue<TimerTask> queue = new PriorityQueue<>();
    public Timer(){
        Thread thread = new Thread(()-> {
            while (true) {
                synchronized (loker1) {
                    while (queue.isEmpty()) {//创建timer时没有submit任务
                        try {
                            loker1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    TimerTask timerTask = queue.peek();
                    if (System.currentTimeMillis() >= timerTask.getTime()) {//gai jin
                        timerTask.run();//如果执行时间到了 就执行并且排出堆
                        queue.poll();
                    } else {
                        try {
                            loker1.wait(timerTask.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }

        });
        thread.start();
    }
    public void submit(Runnable runnable,int time){
        synchronized (loker1){
            TimerTask timerTask  = new TimerTask(time,runnable);
            queue.offer(timerTask);
            loker1.notify();
        }
    }
}
public class Demo23 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.submit(()->{
            System.out.println("hello timer1");
        },1000);
        timer.submit(()->{
            System.out.println("hello timer2");
        },2000);
        timer.submit(()->{
            System.out.println("hello timer3");
        },3000);
    }

}
